from mysql.connector import pooling

# 配置数据库连接参数
db_config = {
    'pool_name': 'my_pool',
    'pool_size': 5,  # 连接池中的连接数
    'host': 'localhost',
    'user': 'root',
    'password': 'root',
    'database': 'yalu',
}

# 创建连接池
conn_pool = pooling.MySQLConnectionPool(**db_config)


def login(username, password):
    # 返回值对应状态
    # 第一个返回值为 登录成功否 True or False
    # 第二个返回值为 登录成功后的权限等级 0 1
    try:
        # 获取连接对象
        conn = conn_pool.get_connection()
        # 创建游标对象
        cursor = conn.cursor()
        try:
            query = f"SELECT * FROM user WHERE username = '{username}' AND password = '{password}'"
            cursor.execute(query)
            # 获取查询结果
            result = cursor.fetchall()
            if len(result) == 1:
                return True, result[0][3]
            else:
                return False, 0
        finally:
            # 关闭游标
            cursor.close()

    finally:
        # 将连接放回连接池
        if conn.is_connected():
            conn.close()


def register(username, password):
    # 返回值对应状态
    # fail          失败  (出错)
    # registered    已被注册
    # success       成功
    try:
        # 获取连接对象
        conn = conn_pool.get_connection()
        # 创建游标对象
        cursor = conn.cursor()
        try:
            # 注册先判断是否已注册
            query = f"SELECT * FROM user WHERE username = '{username}'"
            cursor.execute(query)
            cursor.fetchall()
            if cursor.rowcount > 0:
                return 'registered'
            else:
                query = "INSERT INTO user (username, password) VALUES (%s, %s);"
                cursor.execute(query, (username, password))
                conn.commit()
                if cursor.rowcount > 0:
                    return 'success'
                else:
                    return 'fail'
        finally:
            cursor.close()

    finally:
        if conn.is_connected():
            conn.close()
